import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';

@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss'],
})
export class Tab3Page {
  constructor(public http: HttpClient) {}
  data = [];
  // ionic的组件周期,页面显示时
  ionViewDidEnter() {
    // http://www.codeboy.com:9999/data/cart/list.php
    const url = '/xuezi/data/cart/list.php';
    // 凡是需要登录验证 都需要配置跨域
    this.http.get(url, { withCredentials: true }).subscribe((res: any) => {
      console.log(res);
      this.data = res.data;
    });
  }
  // 购车商品数量修改
  updateCount(index, num) {
    const { iid, count } = this.data[index];
    const new_count = count * 1 + num;
    const url = `/xuezi/data/cart/update_count.php?iid=${iid}&count=${new_count}`;
    this.http.get(url, { withCredentials: true }).subscribe((res: any) => {
      console.log(res);
      if (res.code == 200) {
        this.data[index].count = new_count;
      }
    });
  }
  // 删除购物车中的商品
  doDel(index) {
    const { iid } = this.data[index];
    const url = '/xuezi/data/cart/del.php?iid='+iid;
    this.http.get(url, { withCredentials: true }).subscribe((res: any) => {
      console.log(res);
      if (res.code == 200) {
        // 删除本地数据
        this.data.splice(index,1)
      }else{
        alert('删除商品失败了!')
      }
    });
  }
}
